package com.ruoyi.auth;

import com.ruoyi.common.core.context.AuthTenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 租户数据源切面
 * 
 * @author zhuzhoulin
 */
@Slf4j
@Aspect
@Component
public class AuthTenantDataSourceAspect implements Ordered {

    /**
     * 拦截所有controller public 方法
     */
    @Pointcut("execution(public * com.ruoyi.auth.controller..*.*(..))")
    public void controllerMethodPointcut() {
    }

    /**
     * 环绕切面 根据租户切换数据源
     * @param point  /
     * @return Object  /
     * @throws Throwable /
     */
    @Around("controllerMethodPointcut()")
    public Object controllerAround(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        try {
            result =  point.proceed();
        }catch (Exception e){
            result = e;
            throw e;
        } finally {
            AuthTenantContextHolder.remove();
        }
        return result;
    }


    /**
     * 确保在权限认证aop执行前执行
     */
    @Override
    public int getOrder()
    {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
